package com.ztesoft.sca.dao;

import java.sql.Types;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class TaskResultDaoImpl implements TaskResultDao{

    private JdbcTemplate jdbcTemplate;

    @Autowired
    public TaskResultDaoImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

	@Override
	public void addTaskResult(String aliTaskId, String resultInfo) {
        StringBuffer sqlBuf =new StringBuffer("select TASK_ID from SCA_TASK where ALITASKID=?");
        Object[] param = new Object[]{aliTaskId};
    	String taskId = (String)this.jdbcTemplate.queryForObject(sqlBuf.toString(), param, String.class);
        Long taskIdStr=Long.parseLong(taskId.toString());
		
        StringBuffer sqlBufResule =new StringBuffer("select count(TASK_ID) as count from SCA_TASK_RESULT where TASK_ID=?");
        Object[] paramResult = new Object[]{taskIdStr};
    	int count = (int)this.jdbcTemplate.queryForObject(sqlBufResule.toString(), paramResult, int.class);
    	
    	NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(jdbcTemplate.getDataSource());
    	MapSqlParameterSource paramSource = new MapSqlParameterSource();  
    	String resultContentStr=resultInfo.toString();
        paramSource.addValue("taskId", taskIdStr);  
        paramSource.addValue("resultContent", resultContentStr, Types.CLOB); 
        String sqlStr = "";
        //存在则更新
        if(count>0){
        	sqlStr = "update SCA_TASK_RESULT set RESULT_CONTENT=:resultContent where TASK_ID=:taskId ";  
        }else{
	        //不存在则插入
        	sqlStr = "INSERT INTO SCA_TASK_RESULT (RESULT_ID,TASK_ID,RESULT_CONTENT) VALUES (SCA_TASK_RESULT_SEQ.nextval,:taskId,:resultContent)";  
        }
        template.update(sqlStr, paramSource);  
	}


}
